﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using EmployeeOrdersScope;
using Microsoft.Synchronization.ClientServices.IsolatedStorage;
using System.Collections.ObjectModel;

namespace Klient.Forms
{
    public partial class MyOrders : PhoneApplicationPage
    {
        #region Dependency Property
        public static DependencyProperty AllOrdersProperty = DependencyProperty.Register(
            "AllOrders", typeof(ObservableCollection<Orders>), typeof(MyOrders), null);
        public ObservableCollection<Orders> AllOrders
        {
            get
            {
                return (ObservableCollection<Orders>)GetValue(AllOrdersProperty);
            }
            set
            {
                SetValue(AllOrdersProperty, value);
            }
        }
        #endregion

        private string employeeID;
        EmployeeOrdersScopeOfflineContext orderContext;
        bool isCacheOpen = false;
        bool isCacheBusy = false;

        public MyOrders()
        {
            DataContext = this;
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            NavigationContext.QueryString.TryGetValue("employeeID", out employeeID);

            orderContext = new EmployeeOrdersScopeOfflineContext(
                "orders" + employeeID, 
                new Uri("http://localhost:4000/EmployeeOrdersScopeSyncService.svc/"));

            orderContext.CacheController.ControllerBehavior.AddScopeParameters(
                "employeeID", employeeID);

            orderContext.CacheController.ControllerBehavior.SerializationFormat =
                Microsoft.Synchronization.ClientServices.SerializationFormat.ODataAtom;
            orderContext.CacheController.RefreshCompleted += 
                new EventHandler<Microsoft.Synchronization.ClientServices.RefreshCompletedEventArgs>(
                    CacheController_RefreshCompleted);
            orderContext.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(
                context_LoadCompleted);

            this.Loaded += new RoutedEventHandler(MyOrders_Loaded);

            isCacheOpen = true;
        }

        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            if (isCacheBusy)
            {
                e.Cancel = true;
                return;
            }
            isCacheOpen = false;
            orderContext.Close();
            base.OnNavigatingFrom(e);
        }

        void MyOrders_Loaded(object sender, RoutedEventArgs e)
        {
            if (isCacheOpen & !isCacheBusy)
            {
                progressBar.Visibility = Visibility.Collapsed;
                orderContext.LoadAsync();
            }
        }

        void context_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            Dispatcher.BeginInvoke(
                delegate
                {
                    if (isCacheOpen)
                    {
                        AllOrders = new ObservableCollection<Orders>(
                            orderContext.OrdersCollection);
                    }
                });
        }

        void CacheController_RefreshCompleted(object sender, 
            Microsoft.Synchronization.ClientServices.RefreshCompletedEventArgs e)
        {
            isCacheBusy = false;
            if (isCacheOpen & !isCacheBusy)
            {
                AllOrders = new ObservableCollection<Orders>(
                    orderContext.OrdersCollection);
                progressBar.Visibility = Visibility.Collapsed;
            }
            if (e.Error != null)
                Dispatcher.BeginInvoke(delegate { MessageBox.Show(e.Error.ToString()); });
        }

        private void refreshBtn_Click(object sender, RoutedEventArgs e)
        {
            if (isCacheOpen & !isCacheBusy)
            {
                isCacheBusy = true;
                progressBar.Visibility = Visibility.Visible;
                orderContext.SaveChanges();
                orderContext.CacheController.RefreshAsync();
            }
        }

        private void infoBtn_Click(object sender, RoutedEventArgs e)
        {
            Orders order = (Orders)ordersList.SelectedItem;
            if (order != null)
                NavigationService.Navigate(new Uri(
                    "/Forms/MyCustomers.xaml?customerID=" + order.CustomerID,
                    UriKind.Relative));
        }
    }
}